package net.sudot.chess.business.dao;

import net.sudot.chess.business.model.OrderRecharge;
import net.sudot.commons.pagination.Pageable;
import org.springframework.stereotype.Repository;

import javax.persistence.TypedQuery;
import java.time.Instant;
import java.util.List;

/**
 * 充值订单
 *
 * @author tangjialin on 2018-03-21.
 */
@Repository
public class OrderRechargeDao extends BaseDao<OrderRecharge> {

    /**
     * 获取订单列表
     *
     * @param page   分页参数
     * @param userId 用户主键
     * @return 返回订单列表
     */
    public List<OrderRecharge> findList(Pageable page, Long userId) {
        String ql = "SELECT orders FROM OrderRecharge orders WHERE orders.userId = :userId ORDER BY orders.createdDate DESC";
        TypedQuery<OrderRecharge> query = entityManager.createQuery(ql, OrderRecharge.class);
        query.setParameter("userId", userId);
        settingPagination(query, page);
        return query.getResultList();
    }

    /**
     * 获取用户所有已完成的充值订单
     *
     * @param userId 用户主键
     * @return 返回用户所有已完成的充值订单
     */
    public List<OrderRecharge> findListCompleted(Long userId) {
        String ql = "SELECT orders FROM OrderRecharge orders WHERE orders.userId = :userId AND orders.status = :status";
        TypedQuery<OrderRecharge> query = entityManager.createQuery(ql, OrderRecharge.class);
        query.setParameter("userId", userId);
        query.setParameter("status", OrderRecharge.Status.COMPLETED);
        return query.getResultList();
    }

    /**
     * 获取所有已过期的充值订单
     *
     * @return 返回所有已过期的充值订单
     */
    public List<OrderRecharge> findListExpired() {
        String ql = "SELECT orders FROM OrderRecharge orders WHERE orders.status = :status AND orders.expire < :date";
        TypedQuery<OrderRecharge> query = entityManager.createQuery(ql, OrderRecharge.class);
        query.setParameter("status", OrderRecharge.Status.PENDING_PAYMENT);
        query.setParameter("date", Instant.now());
        return query.getResultList();
    }
}
